
package com.hlkj.pay.app.merchant.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.id.IdUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.IAcctAccountAppService;
import com.hlkj.pay.app.merchant.IMerchantInfoApplicationAppService;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.common.PayResultCode;
import com.hlkj.pay.dto.fund.FundConfigQueryDto;
import com.hlkj.pay.dto.merchant.CashierConfigDto;
import com.hlkj.pay.dto.merchant.MerchantAppQueryDto;
import com.hlkj.pay.dto.merchant.RouterConfigDto;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.hlkj.pay.infrastructure.model.merchant.fund.MerchantFundAccountConfigDO;
import com.hlkj.pay.infrastructure.model.pay.PayChannelDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderInfoDO;
import com.hlkj.pay.service.common.IBusinessLogService;
import com.hlkj.pay.service.merchant.IMerchantApplicationService;
import com.hlkj.pay.service.merchant.IMerchantConfigService;
import com.hlkj.pay.service.merchant.IMerchantService;
import com.hlkj.pay.service.pay.IPayChannelService;
import com.hlkj.pay.service.pay.IProviderService;
import com.hlkj.pay.task.CommonTasks;
import com.hlkj.pay.vo.common.req.CommonUpdateStatusReq;
import com.hlkj.pay.vo.merchant.req.UpdateStatusReq;
import com.hlkj.pay.vo.merchant.resp.app.MerchantAppChannelDetailResp;
import com.hlkj.pay.vo.merchant.resp.app.MerchantAppResp;
import com.hlkj.pay.vo.merchant.resp.info.MerchantFeeConfigResp;
import com.hlkj.pay.vo.openapi.fund.req.OpenApiFundAccountBindReq;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/09/28 15:21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantInfoApplicationAppServiceImpl implements IMerchantInfoApplicationAppService {

    private final IMerchantService merchantService;
    private final IMerchantConfigService merchantConfigService;

    private final IMerchantApplicationService merchantApplicationService;

    private final IAcctAccountAppService acctAccountAppService;

    private final IBusinessLogService businessLogService;

    private final IPayChannelService payChannelService;

    private final IProviderService providerService;

    private final CommonTasks commonTasks;

    @Override
    public CommonResult<String> saveMerchantApp(MerchantAppResp merchantAppReq) {
        log.info("saveMerchantApp merchantAppReq:{}", JsonUtils.toJsonString(merchantAppReq));
        try {
            MerchantInfoDO merchantInfoDO = merchantService.queryMerchant(merchantAppReq.getSn());
            if (merchantInfoDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_NOT_EXIST);
            }
            MerchantAppQueryDto merchantInfoQueryDO = new MerchantAppQueryDto();
            merchantInfoQueryDO.setSn(merchantAppReq.getSn());
            merchantInfoQueryDO.setAppName(merchantAppReq.getAppName());
            merchantInfoQueryDO.setPageNo(1);
            merchantInfoQueryDO.setPageSize(1);
            PageResult<MerchantAppDO> merchantAppDOPageResult = merchantApplicationService.queryPage(merchantInfoQueryDO);
            if (!CollectionUtils.isEmpty(merchantAppDOPageResult.getList())) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_EXIST);
            }
            String appId = merchantApplicationService.generateAppId();
            if (!StringUtils.hasText(appId)) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_SAVE_ERROR);
            }
            MerchantAppDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppReq, MerchantAppDO.class);
            updateMerchantAppDO.setAppId(appId);
            updateMerchantAppDO.setSysType(LocalContext.get().getSysType());
            updateMerchantAppDO.setMd5Key(DigestUtil.md5Hex(merchantInfoDO.getAccount() + merchantInfoDO.getSn() + appId));
            merchantApplicationService.saveMerchantApp(updateMerchantAppDO);
            return CommonResult.success(appId);
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> updateMerchantApp(MerchantAppResp merchantInfoUpdateReq) {
        log.info("updateMerchantApp merchantInfoUpdateReq:{}", JsonUtils.toJsonString(merchantInfoUpdateReq));
        try {
            MerchantAppDO merchantAppDO = merchantApplicationService.queryDetail(merchantInfoUpdateReq.getId());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            MerchantAppDO updateMerchantAppDO = BeanUtil.copyProperties(merchantInfoUpdateReq, MerchantAppDO.class);
            merchantApplicationService.updateMerchantApp(updateMerchantAppDO, merchantAppDO.getAppId());
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }

    }

    @Override
    public CommonResult<Void> updateMerchantAppStatus(CommonUpdateStatusReq commonUpdateStatusReq) {
        log.info("updateMerchantAppStatus commonUpdateStatusReq:{}", JsonUtils.toJsonString(commonUpdateStatusReq));
        try {
            MerchantAppDO merchantAppDO = merchantApplicationService.queryDetail(commonUpdateStatusReq.getId());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            merchantApplicationService.updateMerchantAppStatus(merchantAppDO.getAppId(), commonUpdateStatusReq.getStatus());
            MerchantAppDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppDO, MerchantAppDO.class);
            updateMerchantAppDO.setStatus(commonUpdateStatusReq.getStatus());
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> delMerchantApp(Long id) {
        log.info("delMerchantApp id:{}", id);
        try {
            MerchantAppDO merchantAppDO = merchantApplicationService.queryDetail(id);
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            merchantApplicationService.delMerchantAppByAppId(merchantAppDO.getAppId(), id);
            MerchantAppDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppDO, MerchantAppDO.class);
            updateMerchantAppDO.setDeleteFlag(true);
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<String> saveMerchantAppChannel(MerchantAppChannelDetailResp saveMerchantAppChannelReq) {
        log.info("saveMerchantAppChannel saveMerchantAppChannelReq:{}", JsonUtils.toJsonString(saveMerchantAppChannelReq));
        try {
            // MerchantInfoDO merchantInfoDO =
            // merchantService.queryMerchant(saveMerchantAppChannelReq.getSn());
            // if (merchantInfoDO == null) {
            // return CommonResult.error(MerchantResultCode.MERCHANT_NOT_EXIST);
            // }
            PayChannelDO payChannelDO = payChannelService.queryByCode(saveMerchantAppChannelReq.getChannelCode());
            if (payChannelDO == null) {
                return CommonResult.error(PayResultCode.PAY_CHANNEL_NOT_EXITS);
            }
            ProviderInfoDO providerInfoDO = providerService.queryByCode(saveMerchantAppChannelReq.getProviderCode());
            if (providerInfoDO == null) {
                return CommonResult.error(PayResultCode.PROVIDER_NOT_EXITS);
            }
            List<ProviderChannelConfigDO> providerChannelConfigList = providerService.queryConfigList(saveMerchantAppChannelReq.getProviderCode());
            if (CollectionUtils.isEmpty(providerChannelConfigList)) {
                return CommonResult.error(PayResultCode.PROVIDER_CHANNEL_NOT_EXITS);
            }
            List<String> channelCodes = providerChannelConfigList.stream().map(providerChannelConfigDO -> providerChannelConfigDO.getChannelCode()).collect(Collectors.toList());
            if (!channelCodes.contains(saveMerchantAppChannelReq.getChannelCode())) {
                return CommonResult.error(PayResultCode.PROVIDER_CHANNEL_NOT_EFFECT);
            }
            MerchantAppDO merchantAppDO = merchantApplicationService.queryDetailByAppId(saveMerchantAppChannelReq.getAppId());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            // MerchantAppQueryDto merchantInfoQueryDO = new MerchantAppQueryDto();
            // merchantInfoQueryDO.setAppId(saveMerchantAppChannelReq.getAppId());
            // merchantInfoQueryDO.setProviderCode(saveMerchantAppChannelReq.getProviderCode());
            // merchantInfoQueryDO.setChannelCode(saveMerchantAppChannelReq.getChannelCode());
            // merchantInfoQueryDO.setPageNo(1);
            // merchantInfoQueryDO.setPageSize(1);
            // PageResult<MerchantAppChannelListDto> pageResult =
            // merchantApplicationService.queryChannelPage(merchantInfoQueryDO);
            // if (!CollectionUtils.isEmpty(pageResult.getList())) {
            // return CommonResult.error(MerchantResultCode.MERCHANT_APP_CHANNEL_EXIST);
            // }
            MerchantAppChannelDO merchantAppChannelDO = BeanUtil.copyProperties(saveMerchantAppChannelReq, MerchantAppChannelDO.class);
            merchantAppChannelDO.setCode(IdUtils.getSnowflake().nextIdStr());
            merchantAppChannelDO.setAppConfigJson(JsonUtils.toJsonString(saveMerchantAppChannelReq.getAppConfig()));
            merchantAppChannelDO.setPayWayCode(JsonUtils.toJsonString(saveMerchantAppChannelReq.getPayWayCodes()));
            merchantAppChannelDO.setSn(merchantAppDO.getSn());

            // merchantAppChannelDO.setStatus(CommonEnum.YES_NO_TYPE.YES.getCode());
            merchantApplicationService.saveMerchantAppChannel(merchantAppChannelDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> updateMerchantAppChannel(MerchantAppChannelDetailResp updateMerchantAppChannelReq) {
        log.info("updateMerchantAppChannel updateMerchantAppChannelReq:{}", JsonUtils.toJsonString(updateMerchantAppChannelReq));
        try {
            if (!StringUtils.hasText(updateMerchantAppChannelReq.getCode())) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            // MerchantInfoDO merchantInfoDO =
            // merchantService.queryMerchant(updateMerchantAppChannelReq.getSn());
            // if (merchantInfoDO == null) {
            // return CommonResult.error(MerchantResultCode.MERCHANT_NOT_EXIST);
            // }
            PayChannelDO payChannelDO = payChannelService.queryByCode(updateMerchantAppChannelReq.getChannelCode());
            if (payChannelDO == null) {
                return CommonResult.error(PayResultCode.PAY_CHANNEL_NOT_EXITS);
            }
            ProviderInfoDO providerInfoDO = providerService.queryByCode(updateMerchantAppChannelReq.getProviderCode());
            if (providerInfoDO == null) {
                return CommonResult.error(PayResultCode.PROVIDER_NOT_EXITS);
            }
            List<ProviderChannelConfigDO> providerChannelConfigList = providerService.queryConfigList(updateMerchantAppChannelReq.getProviderCode());
            if (CollectionUtils.isEmpty(providerChannelConfigList)) {
                return CommonResult.error(PayResultCode.PROVIDER_CHANNEL_NOT_EXITS);
            }
            List<String> channelCodes = providerChannelConfigList.stream().map(providerChannelConfigDO -> providerChannelConfigDO.getChannelCode()).collect(Collectors.toList());
            if (!channelCodes.contains(updateMerchantAppChannelReq.getChannelCode())) {
                return CommonResult.error(PayResultCode.PROVIDER_CHANNEL_NOT_EFFECT);
            }
            MerchantAppDO merchantAppDO = merchantApplicationService.queryDetailByAppId(updateMerchantAppChannelReq.getAppId());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(updateMerchantAppChannelReq.getCode());
            if (merchantAppChannelDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
            }
            MerchantAppChannelDO updateMerchantAppDO = BeanUtil.copyProperties(updateMerchantAppChannelReq, MerchantAppChannelDO.class);
            updateMerchantAppDO.setAppConfigJson(JsonUtils.toJsonStringNotNull(updateMerchantAppChannelReq.getAppConfig()));
            updateMerchantAppDO.setPayWayCode(JsonUtils.toJsonString(updateMerchantAppChannelReq.getPayWayCodes()));
            updateMerchantAppDO.setSn(merchantAppDO.getSn());
            updateMerchantAppDO.setId(merchantAppChannelDO.getId());
            merchantApplicationService.updateMerchantAppChannel(updateMerchantAppDO, merchantAppChannelDO.getCode());
            businessChangeLog(merchantAppChannelDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }

    }

    @Override
    public CommonResult<Void> updateMerchantAppChannelStatus(UpdateStatusReq updateStatusReq) {
        log.info("updateMerchantAppChannelStatus updateStatusReq:{}", JsonUtils.toJsonString(updateStatusReq));
        try {
            MerchantAppChannelDO merchantAppDO = merchantApplicationService.queryAppChannelDetail(updateStatusReq.getCode());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            merchantApplicationService.updateMerchantAppChannelStatus(merchantAppDO.getCode(), updateStatusReq.getStatus(), merchantAppDO.getSn(), merchantAppDO.getAppId());
            MerchantAppChannelDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppDO, MerchantAppChannelDO.class);
            updateMerchantAppDO.setStatus(updateStatusReq.getStatus());
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }
    @Override
    public CommonResult<Void> updateLimitRouter(UpdateStatusReq updateStatusReq) {
        log.info("updateLimitRouter updateStatusReq:{}", JsonUtils.toJsonString(updateStatusReq));
        try {
            MerchantAppChannelDO merchantAppDO = merchantApplicationService.queryAppChannelDetail(updateStatusReq.getCode());
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            MerchantAppChannelDO merchantAppChannelDO=new MerchantAppChannelDO();
            merchantAppChannelDO.setId(merchantAppDO.getId());
            merchantAppChannelDO.setLimitRouter(updateStatusReq.getStatus());
            merchantApplicationService.updateMerchantAppChannel(merchantAppChannelDO,merchantAppDO.getCode());
            MerchantAppChannelDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppDO, MerchantAppChannelDO.class);
            updateMerchantAppDO.setStatus(updateStatusReq.getStatus());
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> routerConfig(RouterConfigDto routerConfigDto) {
        log.info("routerConfig routerConfigDto:{}", JsonUtils.toJsonString(routerConfigDto));
        try {
            MerchantAppDO appDO = merchantApplicationService.queryDetailByAppId(routerConfigDto.getAppId());
            if (appDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            MerchantAppDO merchantAppChannelDO=new MerchantAppDO();
            merchantAppChannelDO.setId(appDO.getId());
            merchantAppChannelDO.setRouterConfigJson(JsonUtils.toJsonStringNotNull(routerConfigDto));
            merchantApplicationService.updateMerchantApp(merchantAppChannelDO,appDO.getAppId());
            // MerchantAppChannelDO updateMerchantAppDO = BeanUtil.copyProperties(appDO, MerchantAppChannelDO.class);
            // updateMerchantAppDO.setStatus(updateStatusReq.getStatus());
            // businessChangeLog(appDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("routerConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> cashierConfig(CashierConfigDto cashierConfigDto) {
        log.info("cashierConfig cashierConfigDto:{}", JsonUtils.toJsonString(cashierConfigDto));
        try {
            MerchantAppDO appDO = merchantApplicationService.queryDetailByAppId(cashierConfigDto.getAppId());
            if (appDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            MerchantAppDO merchantAppChannelDO=new MerchantAppDO();
            merchantAppChannelDO.setId(appDO.getId());
            merchantAppChannelDO.setCashierConfigJson(JsonUtils.toJsonStringNotNull(cashierConfigDto));
            merchantApplicationService.updateMerchantApp(merchantAppChannelDO,appDO.getAppId());
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("cashierConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> delMerchantAppChannel(String code) {
        log.info("delMerchantAppChannel code:{}", code);
        try {
            if (!StringUtils.hasText(code)) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            MerchantAppChannelDO merchantAppDO = merchantApplicationService.queryAppChannelDetail(code);
            if (merchantAppDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            merchantApplicationService.delMerchantAppChannel(code, merchantAppDO.getSn(), merchantAppDO.getAppId());
            MerchantAppChannelDO updateMerchantAppDO = BeanUtil.copyProperties(merchantAppDO, MerchantAppChannelDO.class);
            updateMerchantAppDO.setDeleteFlag(Boolean.TRUE);
            businessChangeLog(merchantAppDO, updateMerchantAppDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveConfig error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public void addAppChannelInfo(MerchantAccessInfoDO merchantAccessInfoDO, String appChannelParams,String mchChannelCode, MerchantEnum.DATA_RELATION_TYPE dataRelationType) {
        MerchantAppDO merchantAppDO = merchantApplicationService.queryDefaultApp(merchantAccessInfoDO.getSn());
        if (merchantAppDO == null) {
            MerchantAppQueryDto merchantAppQuerySn = new MerchantAppQueryDto();
            merchantAppQuerySn.setSn(merchantAccessInfoDO.getSn());
            PageResult<MerchantAppDO> merchantAppDOPageResult = merchantApplicationService.queryPage(merchantAppQuerySn);
            merchantAppDO = merchantAppDOPageResult.getList().get(0);
        }
        MerchantAppQueryDto merchantAppQueryDto = new MerchantAppQueryDto();
        merchantAppQueryDto.setSn(merchantAccessInfoDO.getSn());
        merchantAppQueryDto.setProviderCode(merchantAccessInfoDO.getProviderCode());
        merchantAppQueryDto.setChannelCode(merchantAccessInfoDO.getChannelCode());
        merchantAppQueryDto.setAccessId(merchantAccessInfoDO.getId());
        merchantAppQueryDto.setAppId(merchantAppDO.getAppId());
        // merchantAppQueryDto.setSubMchId(merchantAccessInfoDO.getSubMchId());
        merchantAppQueryDto.setAccessType(dataRelationType.getCode());
        List<MerchantAppChannelDO> merchantAppSubChannelList = merchantApplicationService.queryChannelInfoList(merchantAppQueryDto);
        if (CollectionUtils.isEmpty(merchantAppSubChannelList)) {
            merchantAppQueryDto = new MerchantAppQueryDto();
            merchantAppQueryDto.setSn(merchantAccessInfoDO.getSn());
            merchantAppQueryDto.setProviderCode(merchantAccessInfoDO.getProviderCode());
            merchantAppQueryDto.setChannelCode(merchantAccessInfoDO.getChannelCode());
            merchantAppQueryDto.setAppId(merchantAppDO.getAppId());
            merchantAppQueryDto.setStatus(CommonEnum.YES_NO_TYPE.YES.getCode());
            // merchantAppQueryDto.setSubMchId(merchantAccessInfoDO.getSubMchId());
            merchantAppSubChannelList = merchantApplicationService.queryChannelInfoList(merchantAppQueryDto);
            MerchantAppChannelDO merchantAppSubChannelDO = new MerchantAppChannelDO();
            if (CollectionUtils.isEmpty(merchantAppSubChannelList)) {
                merchantAppSubChannelDO.setStatus(CommonEnum.YES_NO_TYPE.YES.getCode());
            }
            else {
                log.info("通道之前存在对应的app 默认状态为关闭");
                merchantAppSubChannelDO.setStatus(CommonEnum.YES_NO_TYPE.NO.getCode());
            }
            merchantAppSubChannelDO.setType(MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_SPECIAL.getCode());
            merchantAppSubChannelDO.setSn(merchantAccessInfoDO.getSn());

            if(StrUtil.isEmpty(mchChannelCode)){
                mchChannelCode = IdUtils.getSnowflake().nextIdStr();
            }

            merchantAppSubChannelDO.setCode(mchChannelCode);
            merchantAppSubChannelDO.setProviderCode(merchantAccessInfoDO.getProviderCode());
            merchantAppSubChannelDO.setChannelCode(merchantAccessInfoDO.getChannelCode());

            // 直付通 设置默认分账
            if(merchantAccessInfoDO.getChannelCode().equals(MerchantExtConstant.CHANNEL_ALI_PAY_ZFT)){
                merchantAppSubChannelDO.setFundProcessType(PayOrderEnums.FUND_PROCESS_TYPE.MERCHANT.getCode());
            }

            merchantAppSubChannelDO.setAccessId(merchantAccessInfoDO.getId());
            merchantAppSubChannelDO.setAppConfigJson(appChannelParams);
            merchantAppSubChannelDO.setAppId(merchantAppDO.getAppId());
            merchantAppSubChannelDO.setSubMchId(merchantAccessInfoDO.getSubMchId());
            // 支付方式默认给商户所有
            MerchantConfigDO merchantConfigDO = merchantConfigService.queryConfig(merchantAccessInfoDO.getSn());
            if (StringUtils.hasText(merchantConfigDO.getFeeConfig())) {
                List<MerchantFeeConfigResp> providerChannelFeeConfigList = JsonUtils.parseArray(merchantConfigDO.getFeeConfig(), MerchantFeeConfigResp.class);
                List<String> payWayCodes = providerChannelFeeConfigList.stream()
                        .filter(merchantFeeConfigResp -> CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantFeeConfigResp.getStatus()))
                        .map(merchantFeeConfigResp -> merchantFeeConfigResp.getPayWayCode()).collect(Collectors.toList());
                merchantAppSubChannelDO.setPayWayCode(JsonUtils.toJsonString(payWayCodes));
            }
            merchantAppSubChannelDO.setAccessType(dataRelationType.getCode());
            merchantApplicationService.saveMerchantAppChannel(merchantAppSubChannelDO);
        }
        else {
            MerchantAppChannelDO merchantAppChannelDO = merchantAppSubChannelList.get(0);
            Map<String, String> oldParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), Map.class);
            Map<String, String> newParams = JsonUtils.parseObject(appChannelParams, Map.class);
            Set<String> keySet = oldParams.keySet();
            newParams.forEach((key, value) -> {
                if (!keySet.contains(key) || !StringUtils.hasText(oldParams.get(key))) {
                    oldParams.put(key, value);
                }
            });
            MerchantAppChannelDO updateMerchantAppChannelDO = new MerchantAppChannelDO();
            updateMerchantAppChannelDO.setAppConfigJson(JsonUtils.toJsonString(oldParams));
            updateMerchantAppChannelDO.setId(merchantAppChannelDO.getId());
            updateMerchantAppChannelDO.setSn(merchantAppChannelDO.getSn());
            updateMerchantAppChannelDO.setAppId(merchantAppChannelDO.getAppId());
            updateMerchantAppChannelDO.setSubMchId(merchantAccessInfoDO.getSubMchId());
            merchantApplicationService.updateMerchantAppChannel(updateMerchantAppChannelDO, merchantAppChannelDO.getCode());
        }

        try{
            // 服务商渠道 更新分账信息
            FundConfigQueryDto fundConfigQueryDto = new FundConfigQueryDto();
            fundConfigQueryDto.setType(MerchantEnum.FUND_TYPE.P_CHANNEL.getCode());
            fundConfigQueryDto.setProviderCode(merchantAccessInfoDO.getProviderCode());
            fundConfigQueryDto.setChannelCode(merchantAccessInfoDO.getChannelCode());
            fundConfigQueryDto.setStatus(1);
            log.info("addAppChannelInfo 查询服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 请求参数:{}",merchantAccessInfoDO.getChannelCode(),mchChannelCode, JSONUtil.toJsonStr(fundConfigQueryDto));
            List<MerchantFundAccountConfigDO> fundAccountConfigDOList = acctAccountAppService.accountConfigList(fundConfigQueryDto);
            log.info("addAppChannelInfo 查询服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 返回参数:{}",merchantAccessInfoDO.getChannelCode(), mchChannelCode,JSONUtil.toJsonStr(fundConfigQueryDto));
            if(CollUtil.isNotEmpty(fundAccountConfigDOList)){
                log.info("addAppChannelInfo 查询服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 size:{}",merchantAccessInfoDO.getChannelCode(), mchChannelCode,fundAccountConfigDOList.size());
                for(MerchantFundAccountConfigDO fundAccountConfigDO : fundAccountConfigDOList){
                    commonTasks.accAccountBind(fundAccountConfigDO,merchantAccessInfoDO,mchChannelCode);
                }
            }

            // 商户服务商渠道 更新分账信息
            fundConfigQueryDto = new FundConfigQueryDto();
            fundConfigQueryDto.setStatus(1);
            fundConfigQueryDto.setType(MerchantEnum.FUND_TYPE.SP_CHANNEL.getCode());
            fundConfigQueryDto.setSn(merchantAccessInfoDO.getSn());
            fundConfigQueryDto.setProviderCode(merchantAccessInfoDO.getProviderCode());
            fundConfigQueryDto.setChannelCode(merchantAccessInfoDO.getChannelCode());
            log.info("addAppChannelInfo 查询商户服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 请求参数:{}",merchantAccessInfoDO.getChannelCode(),mchChannelCode, JSONUtil.toJsonStr(fundConfigQueryDto));
            fundAccountConfigDOList = acctAccountAppService.accountConfigList(fundConfigQueryDto);
            log.info("addAppChannelInfo 查询商户服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 返回参数:{}",merchantAccessInfoDO.getChannelCode(), mchChannelCode,JSONUtil.toJsonStr(fundConfigQueryDto));
            if(CollUtil.isNotEmpty(fundAccountConfigDOList)){
                log.info("addAppChannelInfo 查询商户服务商渠道：{}，通道编码：{} 开通默认分账 查询分账 size:{}",merchantAccessInfoDO.getChannelCode(), mchChannelCode,fundAccountConfigDOList.size());
                for(MerchantFundAccountConfigDO fundAccountConfigDO : fundAccountConfigDOList){
                    commonTasks.accAccountBind(fundAccountConfigDO,merchantAccessInfoDO,mchChannelCode);
                }
            }
        }catch (Exception e){
            log.error("addAppChannelInfo syncAccAccount fail:{}",e);
        }
    }

    private void accountBind(MerchantFundAccountConfigDO fundAccountConfigDO,MerchantAccessInfoDO merchantAccessInfoDO,String mchChannelCode){
        if(fundAccountConfigDO != null){
            log.info("addAppChannelInfo 渠道：{}，通道编码：{} 开通默认分账 请求参数:{}",merchantAccessInfoDO.getChannelCode(),mchChannelCode, JSONUtil.toJsonStr(fundAccountConfigDO));
            // 绑定默认的分账账号
            String accName = fundAccountConfigDO.getName();
            String accNo = fundAccountConfigDO.getAccountNo();
            Integer snVisible = fundAccountConfigDO.getSnVisible() == null ? 0: fundAccountConfigDO.getSnVisible();
            if(StrUtil.isNotEmpty(accName) && StrUtil.isNotEmpty(accNo)){
                // 分账比例
                OpenApiFundAccountBindReq bindReq = new OpenApiFundAccountBindReq();
                bindReq.setName(accName);
                bindReq.setAccountNo(accNo);
                bindReq.setFee(fundAccountConfigDO.getFee());
                bindReq.setRate(fundAccountConfigDO.getRate());
                bindReq.setMchChannelCode(mchChannelCode);
                bindReq.setSnVisible(snVisible);
                bindReq.setFundProcessType(1);
                CommonResult<Void> commonResult = acctAccountAppService.accountBind(bindReq);
                if(commonResult.isSuccess()){
                    log.info("addAppChannelInfo 渠道：{}，通道编码：{} 开通默认分账 成功",merchantAccessInfoDO.getChannelCode(),mchChannelCode);
                }else{
                    log.info("addAppChannelInfo 渠道：{}，通道编码：{} 开通默认分账 失败:{}", merchantAccessInfoDO.getChannelCode(),mchChannelCode,commonResult.getMsg());
                }
            }
        }
    }

    /**
     * log object
     *
     * @param beforeMerchantInfo
     * @param afterPayMerchantInfo
     * @return
     */
    void businessChangeLog(MerchantAppDO beforeMerchantInfo, MerchantAppDO afterPayMerchantInfo) {
        businessLogService.addBusinessChangeLog(beforeMerchantInfo.getId().toString(), MerchantEnum.CHANGE_LOG_TYPE.MERCHANT_APP.getCode(),
                CommonEnum.CHANGE_LOG_MODEL_TYPE.MERCHANT, beforeMerchantInfo, afterPayMerchantInfo);
    }

    /**
     * log object
     *
     * @param beforeMerchantInfo
     * @param afterPayMerchantInfo
     * @return
     */
    void businessChangeLog(MerchantAppChannelDO beforeMerchantInfo, MerchantAppChannelDO afterPayMerchantInfo) {
        businessLogService.addBusinessChangeLog(beforeMerchantInfo.getCode(), MerchantEnum.CHANGE_LOG_TYPE.MERCHANT_APP_CHANNEL.getCode(),
                CommonEnum.CHANGE_LOG_MODEL_TYPE.MERCHANT, beforeMerchantInfo, afterPayMerchantInfo);
    }
}
